package com.yihong.userserver.controller;

import com.alibaba.fastjson.JSON;
import com.yihong.common.util.AjaxJson;
import com.yihong.common.util.JwtUtil;
import com.yihong.userserver.entity.Role;
import com.yihong.userserver.service.RoleService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 *  角色管理
 * @author caorui
 * @date 2019年4月2日17:00:02
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    private Logger LOG = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    /**
     * 查询角色列表
     * @param map
     * @return
     */
    @PostMapping(value = "/listRoles")
    public AjaxJson listRoles(@RequestBody Map<String,Object> map) {
        String name = map.get("name").toString();
        AjaxJson ajaxJson = roleService.listRoles(name);
        return ajaxJson;
    }

    @PostMapping(value = "/updateRoleForIsValid")
    public AjaxJson updateRoleForIsValid(@RequestBody Map<String,Object> map) {
        String id = map.get("id").toString();
        int isValid = Integer.parseInt(map.get("isValid").toString());
        return roleService.updateRoleForIsValid(id,isValid);
    }

    /**
     * 添加角色
     * @param role 角色实体
     * @param request
     * @return
     */
    @PostMapping("/addRole")
    public AjaxJson addRole(@RequestBody Role role, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(token);
        role.setCreateUserId(Long.parseLong(claims.get("userId").toString()));
        role.setCreateTime(new Date());
        AjaxJson result = roleService.saveOrUpdate(role);
        return result;
    }

    @PostMapping("/updateRole")
    public AjaxJson updateRole(@RequestBody Role role, HttpServletRequest request) {
        LOG.info("修改role ===》 " + JSON.toJSONString(role));
        Claims claims = JwtUtil.parseJWT(request.getHeader("Authorization"));
        role.setUpdateUserId(Long.parseLong(claims.get("userId").toString()));
        role.setUpdateTime(new Date());
        return roleService.saveOrUpdate(role);
    }

}
